import pygame
import random
import math

class Tile:
    """方块类，表示游戏中的一个方块元素"""
    
    # 更新方块颜色为更鲜艳、更和谐的颜色
    COLORS = {
        0: (255, 59, 59),     # 鲜红色
        1: (76, 217, 100),    # 翡翠绿
        2: (52, 170, 255),    # 天蓝色
        3: (255, 204, 0),     # 金黄色
        4: (190, 75, 255),    # 紫罗兰
        5: (90, 200, 250),    # 浅蓝色
        6: (255, 149, 0),     # 明橙色
        7: (255, 45, 85)      # 玫红色
    }
    
    # 方块类型的图标（可选用Unicode符号）
    SYMBOLS = {
        0: "●",  # 红色圆点
        1: "★",  # 绿色星星
        2: "◆",  # 蓝色钻石
        3: "▲",  # 黄色三角
        4: "✦",  # 紫色星星
        5: "◎",  # 浅蓝色圆环
        6: "❖",  # 橙色花朵
        7: "❤"   # 粉色心形
    }
    
    def __init__(self, tile_type, row, col, size=50):
        """
        初始化方块
        
        参数:
            tile_type: 方块类型 (整数，对应COLORS中的键)
            row: 方块在游戏板中的行
            col: 方块在游戏板中的列
            size: 方块的大小（像素）
        """
        self.type = tile_type
        self.row = row
        self.col = col
        self.size = size
        self.selected = False
        self.color = self.COLORS.get(tile_type, (150, 150, 150))  # 默认为灰色
        self.symbol = self.SYMBOLS.get(tile_type, "?")
        
        # 方块的位置（像素坐标）
        self.x = col * size
        self.y = row * size
        
        # 动画相关属性
        self.target_x = self.x
        self.target_y = self.y
        self.animating = False
        self.animation_speed = 10
        self.falling = False
        
        # 特效相关属性
        self.scale = 1.0
        self.alpha = 255
        self.vanishing = False
        self.pulse = 0  # 用于呼吸效果
        self.rotation = 0  # 用于旋转效果
        
    def update_position(self, row, col):
        """更新方块的位置"""
        self.row = row
        self.col = col
        self.target_x = col * self.size
        self.target_y = row * self.size
        self.animating = True
        
    def update(self):
        """更新方块的状态，包括动画效果"""
        # 处理移动动画
        if self.animating:
            dx = self.target_x - self.x
            dy = self.target_y - self.y
            
            if abs(dx) < self.animation_speed and abs(dy) < self.animation_speed:
                self.x = self.target_x
                self.y = self.target_y
                self.animating = False
            else:
                self.x += dx * 0.2
                self.y += dy * 0.2
        
        # 处理消除动画
        if self.vanishing:
            self.scale -= 0.05
            self.alpha -= 15
            self.rotation += 10  # 旋转效果
            
            if self.scale <= 0 or self.alpha <= 0:
                self.vanishing = False
                return True  # 表示方块已完全消除
        
        # 处理选中状态的呼吸效果
        if self.selected:
            self.pulse = (self.pulse + 0.1) % (2 * math.pi)
        
        return False
        
    def draw(self, surface, offset_x=0, offset_y=0):
        """
        绘制方块
        
        参数:
            surface: pygame的Surface对象，用于绘制
            offset_x: x坐标偏移量
            offset_y: y坐标偏移量
        """
        rect = pygame.Rect(
            self.x + offset_x, 
            self.y + offset_y, 
            self.size, 
            self.size
        )
        
        if self.vanishing:
            # 创建临时surface以支持透明度和旋转
            temp_surface = pygame.Surface((self.size, self.size), pygame.SRCALPHA)
            scaled_size = int(self.size * self.scale)
            
            # 计算缩放后的位置偏移
            scale_offset = (self.size - scaled_size) // 2
            
            # 创建方块的绘制矩形
            inner_rect = pygame.Rect(scale_offset, scale_offset, scaled_size, scaled_size)
            
            # 绘制圆角方块背景
            pygame.draw.rect(
                temp_surface, 
                (*self.color, self.alpha), 
                inner_rect, 
                border_radius=int(self.size * 0.2)
            )
            
            # 添加内部装饰
            smaller_rect = inner_rect.inflate(-inner_rect.width * 0.3, -inner_rect.height * 0.3)
            pygame.draw.rect(
                temp_surface, 
                (255, 255, 255, self.alpha // 3), 
                smaller_rect, 
                border_radius=int(self.size * 0.1)
            )
            
            # 绘制边框
            pygame.draw.rect(
                temp_surface, 
                (255, 255, 255, self.alpha), 
                inner_rect, 
                3, 
                border_radius=int(self.size * 0.2)
            )
            
            # 应用旋转
            if self.rotation:
                rotated_surface = pygame.transform.rotate(temp_surface, self.rotation)
                # 计算旋转后surface的新位置以保持中心点不变
                rot_rect = rotated_surface.get_rect(
                    center=(self.x + self.size // 2 + offset_x, 
                           self.y + self.size // 2 + offset_y)
                )
                surface.blit(rotated_surface, rot_rect)
            else:
                # 如果没有旋转，直接绘制
                surface.blit(temp_surface, (self.x + offset_x, self.y + offset_y))
        else:
            # 绘制普通方块
            # 主体方块，使用圆角矩形
            pygame.draw.rect(
                surface, 
                self.color, 
                rect, 
                border_radius=int(self.size * 0.2)
            )
            
            # 添加内部亮光效果
            inner_rect = rect.inflate(-rect.width * 0.2, -rect.height * 0.2)
            pygame.draw.rect(
                surface, 
                tuple(min(c + 50, 255) for c in self.color), 
                inner_rect, 
                border_radius=int(self.size * 0.1)
            )
            
            # 绘制符号（如果使用符号）
            font = pygame.font.SysFont('simhei', int(self.size * 0.5))
            text = font.render(self.symbol, True, (255, 255, 255))
            text_rect = text.get_rect(center=rect.center)
            surface.blit(text, text_rect)
            
            # 如果被选中，添加呼吸光效果
            if self.selected:
                # 计算呼吸效果的大小变化
                pulse_scale = 1.0 + 0.1 * math.sin(self.pulse)
                highlight_rect = rect.inflate(
                    rect.width * (pulse_scale - 1),
                    rect.height * (pulse_scale - 1)
                )
                
                # 绘制发光边框
                pygame.draw.rect(
                    surface, 
                    (255, 255, 255), 
                    highlight_rect, 
                    3, 
                    border_radius=int(self.size * 0.2)
                )
                
                # 再添加一个半透明的外发光
                glow_rect = rect.inflate(
                    rect.width * (pulse_scale - 0.9),
                    rect.height * (pulse_scale - 0.9)
                )
                
                # 创建临时surface用于绘制半透明发光效果
                glow_surface = pygame.Surface((glow_rect.width, glow_rect.height), pygame.SRCALPHA)
                pygame.draw.rect(
                    glow_surface, 
                    (255, 255, 255, 100), 
                    pygame.Rect(0, 0, glow_rect.width, glow_rect.height),
                    border_radius=int(self.size * 0.25)
                )
                
                # 将发光效果绘制到主surface
                surface.blit(
                    glow_surface, 
                    (glow_rect.left, glow_rect.top)
                )
                
    def is_animating(self):
        """检查方块是否正在动画中"""
        return self.animating or self.vanishing
        
    def start_vanish_animation(self):
        """开始消除动画"""
        self.vanishing = True
        self.scale = 1.0
        self.alpha = 255
        
    def contains_point(self, x, y):
        """检查点(x,y)是否在方块内"""
        return (self.x <= x < self.x + self.size and 
                self.y <= y < self.y + self.size)
                
    @staticmethod
    def get_random_type(max_type=5):
        """生成一个随机的方块类型"""
        return random.randint(0, max_type) 